import fs from 'fs';
import { fork } from 'child_process';
import chokidar from 'chokidar';  // 使用 chokidar 替代 fs.watchFile
import dotenv from 'dotenv';
import { fileURLToPath } from 'url';
import path from 'path';
// 路径设置
import http from 'http';
import https from 'https';


const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const parentDir = path.dirname(__dirname);


const parentDirx = path.dirname(parentDir);
// 动态导入数据模块
const {bot} = await import(getImportPath(`${parentDirx}/Script/datax.js`));

// 处理路径，确保兼容性
function getImportPath(filePath) {
      // 检查是否是 Windows 系统
        if (process.platform === 'win32') {
                // 在 Windows 系统中添加 file:// 前缀
                    return `file://${filePath}`;
        }
          // 在其他系统中直接返回路径
            return filePath;
}
        

const filepath = `././config/配置.env`;
const config = dotenv.parse(fs.readFileSync(filepath, 'utf8'));

// 打印配置信息
const wexthtml = `http://${config.wextIP}/api?json&key=${config.wextKey}`;
console.log(`\n-------------------------`);
console.log(`载入 *[xiaoxi] 插件正在运行`);
console.log(`-------------------------\n`);



const botFunctions = await bot();
// 监听来自主进程的消息
process.on('message', (requestData) => {
const data=requestData;
console.log(`----[xiaoxi]--------${requestData}-------------\n`);




let wxid=data.data.memid
//微信id
let wixhm=data.data.memalias
//发送人 微信号
let wixmc=data.data.memname
//发送人 微信名
let wixmc2=data.data.nickName2
//发送人 微信群名
let utypex=data.data.utype
//判断 (私聊 群聊)
let nickName=data.data.nickName
//发送人 群名
let qunid=data.data.fromid
//判断 群id （发送id）
if (qunid == config.weixid){
}else if (utypex == "2051" ||  utypex == "2050" ||  utypex == "2" ||   utypex == "3"){




 let airports={"昆明长水国际机场":"KMG","郑州新郑国际机场":"CGO","北京首都国际机场":"PEK","深圳宝安国际机场":"SZX","广州白云国际机场":"CAN","武汉天河国际机场":"WUH","成都双流国际机场":"CTU","银川河东国际机场":"INC","兰州中川机场":"LHW","上海虹桥国际机场":"SHA","上海浦东国际机场":"PVG","惠州机场":"HUZ","杭州萧山国际机场":"HGH","贵阳龙洞堡国际机场":"KWE","南京禄口国际机场":"NKG","太原武宿国际机场":"TYN","重庆江北国际机场":"CKG","石家庄正定国际机场":"SJW","厦门高崎国际机场":"XMN","济南遥墙国际机场":"TNA","烟台莱山国际机场":"YNT","喀什机场":"KHG","呼伦贝尔海拉尔机场":"HLD","合肥新桥国际机场":"HFE","海口美兰国际机场":"HAK","长春龙嘉国际机场":"CGQ","揭阳潮汕国际机场":"SWA","台州路桥机场":"HYN","拉萨贡嘎国际机场":"LXA","三亚凤凰国际机场":"SYX","沈阳桃仙国际机场":"SHE","咸阳机场":"XIY","阿克苏机场":"AKU","珠海机场":"ZUH","西宁曹家堡机场":"XNN","库尔勒机场":"KRL","福州长乐国际机场":"FOC","淮安涟水机场":"HIA","克拉玛依机场":"KRY","常州机场":"CZX","呼和浩特白塔国际机场":"HET","湛江机场":"ZHA","黄山屯溪机场":"TXN","北京大兴国际机场":"PKX","武夷山机场":"WUS","鄂尔多斯机场":"DSN","大连周水子国际机场":"DLC","南充机场":"NAO","长沙黄花国际机场":"CSX","乌鲁木齐地窝堡国际机场":"URC","西双版纳嘎洒国际机场":"JHG","敦煌机场":"DNH","满洲里西郊机场":"NZH","临沂机场":"LYI","张家界荷花国际机场":"DYG","赣州黄金国际机场":"KOW","威海国际机场":"WEH","阜阳机场":"FUG","东营胜利机场":"DOY","山海关机场":"SHP","天津滨海国际机场":"TSN","格尔木机场":"GOQ","绵阳机场":"MIG","西安西关机场":"SIA","无锡苏南硕放国际机场":"WUX","九华山机场":"JUH","长白山机场":"NBS","泉州晋江国际机场":"JJN","徐州观音国际机场":"XUZ","阿尔泰机场":"AAT","芒市机场":"LUM","南昌昌北国际机场":"KHN","包头机场":"BAV","安庆机场":"AQG","临汾乔李机场":"LFQ","延吉朝阳川机场":"YNJ","济宁曲阜机场":"JNG","温州龙湾国际机场":"WNZ","安顺黄果树机场":"AVA","恩施机场":"ENH","哈尔滨太平国际机场":"HRB","井冈山机场":"JGS","北京南苑机场":"NAY","遵义新舟机场":"ZYI","乌兰浩特机场":"HLH","佛山沙堤机场":"FUO","南宁吴圩国际机场":"NNG","南通兴东机场":"NTG","宁波栎社国际机场":"NGB","乌海机场":"WUA","常德机场":"CGD","攀枝花保安营机场":"PZI","通辽机场":"TGO","林芝米林机场":"LZY","义乌机场":"YIW","中卫沙坡头机场":"ZHY","丽江三义国际机场":"LJG","伊宁机场":"YIN","梅州梅县机场":"MXZ"}
function findAirportCode(cityName) {
  // 遍历机场数据，寻找匹配的城市名
  for (const [airportName, code] of Object.entries(airports)) {
    if (airportName.includes(cityName)) {
      return code;
    }
  }
  return '0';
}


const regex = /(\D+) 到 (\D+) 查询 (\d{4}-\d{1,2}-\d{1,2}) 到 (\d{4}-\d{1,2}-\d{1,2}) 的机票/;
const match = data.data.msg.match(regex);
if (match) {

let cfdian=findAirportCode(match[1])
//出发点
let daodifan=findAirportCode(match[2])
//到地方

let totalCost=""
if (cfdian == "0" || daodifan == "0"){
totalCost=`喀什徕宁机场 ✈️ 长沙黄花机场\n[不包含保险邮费]\n`
cfdian="KHG"
daodifan="CSX"
}else{
totalCost=`${match[1]}机场 ✈️ ${match[2]}机场\n[不包含保险邮费]\n`
}


  // 将字符串日期转换为Date对象
  const startDate = new Date(match[3]);
  const endDate = new Date(match[4]);
  // 计算两个日期之间的差异（以毫秒为单位）
  const diffInMs = endDate - startDate;

  // 将毫秒转换为天数
  const diffInDays = diffInMs / (1000 * 60 * 60 * 24);

  // 获取今天的日期
  const today = new Date();
  // 将今天的日期设置为00:00:00，以便进行比较
  today.setHours(0, 0, 0, 0);

  // 检查第一个日期是否大于今天
  if (startDate > today) {
    // 检查天数差异是否不超过10天
    if (Math.abs(diffInDays) <= 16) {
const options = {
  method: 'POST',
  hostname: 'wx.17u.cn',
  path: '/mihawkapi/calendar/lowestPrice',
  headers: {
    'User-Agent': 'Mozilla/5.0 (Linux; Android 10; MIX 2S Build/QKQ1.190828.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.101 Mobile Safari/537.36/TcTravel/10.9.7/TcTravel/10.9.7',
    'Accept-Encoding': 'gzip, deflate',
    'traceparent': '00-ab45e97b2eec2d6d34a27d249ee1ec63-5dc01546fa005dd3-01',
    'Content-Type': 'application/json;charset=UTF-8',
    'Origin': 'https://wx.17u.cn',
    'X-Requested-With': 'com.tongcheng.android',
    'Sec-Fetch-Site': 'same-origin',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Dest': 'empty',
    'Referer': 'https://wx.17u.cn/fapp/app/book1?date=2024-11-29&backDate=&childticket=0,0&an=1&cn=0&baby=0&fromCity=%E5%96%80%E4%BB%80%E5%BE%95%E5%AE%81%E6%9C%BA%E5%9C%BA&toCity=%E9%BB%84%E8%8A%B1%E6%9C%BA%E5%9C%BA&fromcitycode=KHG&fromCode=KHG&tocitycode=CSX&toCode=CSX&acn=%E9%95%BF%E6%B2%99&dcn=%E5%96%80%E4%BB%80&refId=&cabin=0&platcode=10189&direct=0&nametype=2,2&frompage=HOME&poikey=&outrefid=',
    'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
    'Cookie': 'traceid=651bb7fc-ba39-4c90-8213-67ca2200bb9f; flightRefId=16359978; __tctmc=0.55333869; __tctmd=0.1; __tctmb=0.3630924255917639.1732794760161.1732794760161.1; __tccgd=0.0; __tctmc=217272534.91911772; __tctmd=217272534.737325; __tctma=217272534.1732794760635846.1732794760303.1732794760303.1732794760303.1; __tctmb=217272534.3666292694936486.1732794760303.1732794760303.1; __tctmu=217272534.0.0; __tctmz=217272534.1732794760303.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none); longKey=1732794760635846; __tctrack=0'
  }
};

const req = http.request(options, function (res) {
  const chunks = [];

  res.on('data', function (chunk) {
    chunks.push(chunk);
  });

  res.on('end', function () {
    const body = Buffer.concat(chunks);
let jsonData=JSON.parse(body)

if (jsonData.data && Array.isArray(jsonData.data)) {
  // 遍历jsonData.data数组
  jsonData.data.forEach(item => {
    // 计算总价格，这里假设额外费用是固定的49+70
  //  const total = item.price + 49 + 70;
    // 使用模板字符串拼接信息
    totalCost += `${item.date} 价钱:${item.price} 元\n`;
  });
} else {
  console.log('没有找到数据');
}
botFunctions.Text(wexthtml,qunid,totalCost)

  });
});

req.write(JSON.stringify({
  "channel": "434",
  "isReturn": false,
  "startDate": match[3],
  "departureDate": "",
  "endDate": match[4],
  "startCity": cfdian,
  "arriveCity": daodifan,
  "scope": 1,
  "direct": false,
  "baseCabinType": 1
}));
req.end()
    } else {
      botFunctions.Text(wexthtml,qunid,`失败：两个日期相差超过15天。`);
    }
  } else {
    botFunctions.Text(wexthtml,qunid,`不可以是今天。`);
  }
}//////////---------------------------------~~~~~~~-------------------


}
});
